package co.fitstart.admin.handler.impl;

import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.demo2do.core.persistence.GenericDaoSupport;

import co.fitstart.admin.handler.UserHandler;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.UserAccount;
import co.fitstart.entity.user.UserSource;

/**
 * 
 * @author wangliwang
 *
 */
@Component("userHandler")
public class UserHandlerImpl implements UserHandler {

	private static final Logger logger = LoggerFactory.getLogger(UserHandlerImpl.class);

	@Autowired
	private GenericDaoSupport genericDaoSupport;

	/*
	 * (non-Javadoc)
	 * 
	 * @see co.fitstart.admin.handler.UserHandler#create(java.lang.String,
	 * java.lang.String, boolean, java.lang.String, java.lang.String)
	 */
	public User create(String mobile, String userName, boolean visitor, String userAccountKey,
			String userAccountValue) {

		// 1. construct user and save to database
		User user = new User(mobile, userName, visitor);
		genericDaoSupport.save(user);

		// 2. construct userAccount and save to database
		UserAccount userAccount = new UserAccount(user, userAccountKey, userAccountValue);
		genericDaoSupport.save(userAccount);

		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserSource> listUserSource(InputStream inputStream) {
		List<UserSource> userSource = (List<UserSource>) this.parse(inputStream);
        return userSource;
	}

	private Object parse(InputStream inputStream) {

		// 0. prepare data
		List<Object> result = new LinkedList<Object>();
		DataFormatter formatter = new DataFormatter();

		try {

			logger.trace("#parse() - Starting parsing upload file.");

			// 1. get workbook
			Workbook workbook = WorkbookFactory.create(inputStream);

			// 2. get sheet and rows
			Sheet sheet = workbook.getSheetAt(0);
			Iterator<Row> rows = sheet.iterator();

			while (rows.hasNext()) {

				Row row = rows.next();
				int rowNum = row.getRowNum();

				if (rowNum <= 1) {
					continue;
				}

				// constructor assessor or delegate
				UserSource userSource = this.initUserSource(formatter, row);
				if (userSource != null) {
					result.add(userSource);
				}

			}

			logger.trace("#parse() - Finishing parsing file with {} records.", result.size());

		} catch (Exception e) {
			logger.error("#parse() - Finishing parsing file with errors.", e);
		}

		return result;

	}

	/**
	 * construct assessor by excel formatter
	 * 
	 * @param formatter
	 * @param row
	 * @return
	 */
	private UserSource initUserSource(DataFormatter formatter, Row row) {

		// construct assessor
		String name = formatter.formatCellValue(row.getCell(0));
		String gender = formatter.formatCellValue(row.getCell(1));
		String phone = formatter.formatCellValue(row.getCell(2));
		String userSourceTypeName = formatter.formatCellValue(row.getCell(3));
		String wechatNumber = formatter.formatCellValue(row.getCell(4));
		String occurDate = formatter.formatCellValue(row.getCell(5));
		String reciverName = formatter.formatCellValue(row.getCell(6));
		String requirement = formatter.formatCellValue(row.getCell(7));
		
		if (StringUtils.isBlank(userSourceTypeName) || StringUtils.isBlank(occurDate)) {
			return null;
		} else {
			return new UserSource(name, phone, gender, wechatNumber, requirement, reciverName, occurDate, userSourceTypeName);
		}

	}

}
